<?php
class Admin_UserController extends Zend_Controller_Action
{
	private $t;

	public function preDispatch()
	{
		$this->t = Zend_Registry::get('Zend_Translate');
		$this->view->t = $this->t;
	}

	public function listAction()
	{
		$this->view->title = $this->t->_('all users');
		$users = new Users();
		$this->view->users = $users->fetchAllInfo();
	}

	public function saveAction()
	{
		$form = new UserForm();

		$this->view->title = $this->t->_('save user');
		$this->view->form = $form;

		$id = (int) $this->_request->getParam('id');

		$users = new Users();
		$userProfiles = new UserProfiles();

		$groups = new Groups();
		$form->groups->setMultiOptions($groups->generateOptions());

		$user = $users->fetchRow("`id` = '{$id}'");
		$userProfile = $userProfiles->fetchRow("`userId` = '{$id}'");

		if($user == NULL) {
			$user = $users->createRow();
			$userProfile = $userProfiles->createRow();
		}

		if($this->_request->isPost()) {
			$formData = $this->_request->getPost();
			if($form->isValid($formData)) {
				$user->username = $form->getValue('username');
				$user->password = $this->_helper->encrypt($form->getValue('password'));

				$userId = $user->save();

				$userProfile->userId = $userId;
				$userProfile->email = $form->getValue('email');
				$userProfile->firstname = $form->getValue('firstname');
				$userProfile->surname = $form->getValue('surname');

				$userProfile->save();

				$selectedGroups = $form->getValue('groups');
				if(is_array($selectedGroups)) {
					$usersGroups = new UsersGroups();
					$usersGroups->delete("`userId` = '{$userId}'");

					foreach($selectedGroups as $selectedGroup) {
						$userGroup = $usersGroups->createRow();
						$userGroup->userId = $userId;
						$userGroup->groupId = $selectedGroup;
						$userGroup->save();
					}
				}
			}
		} else {
			$usersGroups = $user->findManyToManyRowset('Groups', 'UsersGroups');
			$selectedGroups = array();

			foreach($usersGroups as $userGroup) {
				$selectedGroups[] = $userGroup->id;
			}

			$form->populate($user->toArray());
			$form->populate($userProfile->toArray());
			$form->populate(array('groups' => $selectedGroups));
		}
	}

	public function deleteAction()
	{

	}
}